<?php
namespace Admin\Controller;
use Admin\Model\newsModel;
use Think\AjaxPage;
use Think\Page;
class NewsController extends BaseController {
    
    /**
     *  商品列表
     */
    public function newsList() {
        $this->display();
    }
    /**
     *  商品列表
     */
    public function ajaxnewsList() {
        $where = ' 1 = 1 ';
        I('intro') && $where = "$where and " . I('intro') . " = 1";
        // 关键词搜索               
        $key_word = I('key_word') ? trim(I('key_word')) : '';
        if ($key_word) {
            $where = "$where and (news_name like '%$key_word%' or news_sn like '%$key_word%')";
        }
		$customer = I('customer') ? trim(I('customer')) : '';
        if ($customer) {
            $where.= " and customer=".$customer;
        }
        $model = M('news');
        $count = $model->where($where)->count();
        $Page = new AjaxPage($count, 10);
        $show = $Page->show();
        $order_str = "add_time desc";
        $newsList = $model->where($where)->order($order_str)->limit($Page->firstRow . ',' . $Page->listRows)->select();
		$time = strtotime(date('Y-m-d',time()).' 00:00:00')-1;
		foreach((array)$newsList as $k=>$v){
			if(strtotime($v['url'])>$time){
				$newsList[$k]['status'] = 1;
			}else{
				$newsList[$k]['status'] = 0;
			}
		}
        $this->assign('newsList', $newsList);
        $this->assign('page', $show);
        $this->display();
    }
    /**
     * 添加修改商品
     */
    public function addEditnews() {
        $id = I('id')?I('id'):'';
        if($id){
            $act = 'edit';
        }else{
            $act = 'add';
        }
		$this->assign('act',$act);
        $news_list = M('news')->where(array('id'=>$id))->find();
        $this->assign('newsInfo', $news_list);
		$this->initEditor();
        $this->display('_news');
    }
    public function getCategory(){
        $id = I('parent_id')?I('parent_id'):'';
        $mod = M('news_cat');
        $cat_list = $mod->where(array('cat_id'=>$id))->select();
        foreach((array)$cat_list as $k=>$v){
            $html .= '<option value="'.$v['id'].'">'.$v['name'].'</option>';
        }
        echo $html;
    }
    /**
     * 商品类型  用于设置商品的属性
     */
    public function newsTypeList() {
        $model = M("newsType");
        $count = $model->count();
        $Page = new Page($count, 100);
        $show = $Page->show();
        $newsTypeList = $model->order("id desc")->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $this->assign('show', $show);
        $this->assign('newsTypeList', $newsTypeList);
        $this->display('newsTypeList');
    }
    public function addEditnewsForm(){
        $mod = M('news');
        if(IS_POST){
            $data = I('post.');
            if($data['act']=='add'){
                $data['add_time'] = time();
                $result = $mod->add($data);
                if($result){
                    $this->success('添加成功',U('Admin/news/newsList'));
                }else{
                    $this->error('添加失败');
                }
            }else{
                $data['up_time'] = time();
                $result = $mod->where(array('id'=>$data['id']))->save($data);
                if($result){
                    $this->success('编辑成功',U('Admin/news/newsList'));
                }else{
                    $this->error('编辑失败');
                }
            }
        }
    }
	
	public function user() {
		$this->assign('nid',I('id'));
        $this->display();
    }
	
	public function ajaxUser() {
        $condition['a.id'] = I('nid');
        I('user_id') ? $condition['b.id'] = I('user_id') : false;
        I('nickname') ? $condition['b.realname'] = array('like','%'.I('nickname').'%') : false;
		
		$news_mod = M('news');
		
		$count = $news_mod->alias('as a')->join('LEFT JOIN '.C('DB_PREFIX').'users as b on a.title=b.code')->where($condition)->count();
        $Page = new AjaxPage($count, 10);
        $userList = $news_mod->alias('as a')->join('LEFT JOIN '.C('DB_PREFIX').'users as b on a.title=b.code')->where($condition)->order('b.id desc')->limit($Page->firstRow . ',' . $Page->listRows)->select();
        $show = $Page->show();
        $this->assign('userList', $userList);
        $this->assign('page', $show);
        $this->display();
    }
    /**
     * 删除商品
     */
    public function delnews() {
        $news_id = i('id');        
        M("news")->where('id =' . $news_id)->delete(); 
        exit(json_encode(array('code'=>200)));
    }
	
	public function addBatch(){
		$this->display('batch');
	}
	
	public function add_batch(){
		if(IS_POST){
			$data = I('post.');
			if(!$data['title']){
				$this->error('请输入激活码长度');
			}
			if(!$data['number']){
				$this->error('请输入激活码使用次数');
			}
			if(!$data['generate']){
				$this->error('请输入激活码个数');
			}			
			$mod = M('news');
			$add['add_time'] = time();
			$add['number'] = $data['number'];
			$add['cat_id'] = $data['cat_id'];
			for($i=0;$i<$data['generate'];$i++){
				$code = $this->random($data['title'],$data['status']);
				$check = $mod->where(array('title'=>$code))->count();
				if(!$check){
					$add['title'] = $code;
                	$result = $mod->add($add);
				}
			}
			$this->success('生成成功',U('News/newsList'));
		}
	}  
	
	function random($length=6, $type='string', $convert=0){
		$config = array(
			'number'=>'1234567890',
			'letter'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
			'string'=>'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
			'all'=>'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
		);

		if(!isset($config[$type])) $type = 'string';
		$string = $config[$type];

		$code = '';
		$strlen = strlen($string) -1;
		for($i = 0; $i < $length; $i++){
			$code .= $string{mt_rand(0, $strlen)};
		}
		if(!empty($convert)){
			$code = ($convert > 0)? strtoupper($code) : strtolower($code);
		}
		return $code;
	}
    /**
     * 初始化编辑器链接     
     * 本编辑器参考 
     */
    private function initEditor() {
        $this->assign("URL_upload", U('Admin/Ueditor/imageUp', array('savepath' => 'news'))); // 图片上传目录
        $this->assign("URL_imageUp", U('Admin/Ueditor/imageUp', array('savepath' => 'news'))); //  不知道啥图片
        $this->assign("URL_fileUp", U('Admin/Ueditor/fileUp', array('savepath' => 'news'))); // 文件上传s
        $this->assign("URL_scrawlUp", U('Admin/Ueditor/scrawlUp', array('savepath' => 'news')));  //  图片流
        $this->assign("URL_getRemoteImage", U('Admin/Ueditor/getRemoteImage', array('savepath' => 'news'))); // 远程图片管理
        $this->assign("URL_imageManager", U('Admin/Ueditor/imageManager', array('savepath' => 'news'))); // 图片管理        
        $this->assign("URL_getMovie", U('Admin/Ueditor/getMovie', array('savepath' => 'news'))); // 视频上传
        $this->assign("URL_Home", "");
    }
    /**
     * 动态获取商品规格选择框 根据不同的数据返回不同的选择框
     */
    public function ajaxGetSpecSelect() {
        $news_id = $_GET['news_id'] ? $_GET['news_id'] : 0;
        $newsModel = new newsModel();
        //$_GET['spec_type'] =  13;
        $specList = D('Spec')->where("type_id = " . $_GET['spec_type'])->order('`order` desc')->select();
        foreach ($specList as $k => $v) {
            $specList[$k]['spec_item'] = D('SpecItem')->where("spec_id = " . $v['id'])->order('id')->getField('id,item');
        }
        $items_id = M('newsStock')->where('news_id = ' . $news_id)->getField("GROUP_CONCAT(`key` SEPARATOR '_') AS items_id");
        $items_ids = explode('_', $items_id);
        if ($news_id) {
            $specImageList = M('SpecImg')->where("news_id = $news_id")->getField('spec_img_id,src');
        }
        $this->assign('specImageList', $specImageList);
        $this->assign('items_ids', $items_ids);
        $this->assign('specList', $specList);
        $this->display('ajax_spec_select');
    }
    /**
     * 动态获取商品规格输入框 根据不同的数据返回不同的输入框
     */
    public function ajaxGetSpecInput() {
        $newsModel = new newsModel();
        $news_id = $_REQUEST['news_id'] ? $_REQUEST['news_id'] : 0;
        $str = $newsModel->getSpecInput($news_id, $_POST['spec_arr']);
        exit($str);
    }
    /**
     * 删除商品相册图
     */
    public function delnewsImg() {
        $path = I('filename', '');
        $result = M('news_img')->where("images = '$path'")->delete();
        if($result){
            unlink($path);
        }
    }
    //商品评论
    function comment(){
        $mod = M('orders_comment');
        $where = '1=1';
        $keywords = trim(I('keywords'));
        $keywords && $where.=" and (a.order_sn like '%$keywords%' or c.news_name like '%$keywords%')";
        $p = empty($_REQUEST['p']) ? 1 : $_REQUEST['p'];
        $size = 20;
        $count = $mod->alias('as a')->join('left join '.C('DB_PREFIX').'news as c on c.id=a.news_id')->where($where)->count();
        $pager = new \Think\Page($count, $size);
        $page = $pager->show();
        $comment_list = $mod->alias('as a')->where($where)
            ->join('left join '.C('DB_PREFIX').'news as c on c.id=a.news_id')
            ->join('left join '.C('DB_PREFIX').'news_store_spec as b on b.id=a.spec_id')
            ->join('left join '.C('DB_PREFIX').'users as d on d.id=a.user_id')
            ->join('left join '.C('DB_PREFIX').'business as e on e.id=a.store_id')
            ->order('a.add_time desc')
            ->page("$p,$size")
            ->field('a.order_sn,c.news_name,b.spec_name,e.store_name,d.user_name,a.star,a.contents,a.images,a.add_time')
            ->select();
        foreach((array)$comment_list as $k=>$v){
            $v['images'] && $comment_list[$k]['images'] = explode(',',$v['images']);
        }
        $this->assign('comment_list',$comment_list);
        $this->assign('page', $page);
        $this->assign('keywords', $keywords);
        $this->display();
    }
}
